package controller

import (
	myConfig "common/config"
	"common/helper"
	myUserHelp "common/userHelp"
	"encoding/json"
	"fmt"
	"member/model"
	"strconv"
	"strings"
	"time"

	"github.com/valyala/fasthttp"
)

type GameController struct{}

func (that *GameController) Search(ctx *fasthttp.RequestCtx) {

	ty := ctx.QueryArgs().GetUintOrZero("ty")
	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	tagId := string(ctx.QueryArgs().Peek("tag_id"))
	platformId := string(ctx.QueryArgs().Peek("platform_id"))
	w := string(ctx.QueryArgs().Peek("w"))
	if helper.CtypePunct(w) {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}
	if !helper.CtypeDigit(platformId) {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}
	if !helper.CtypeDigit(tagId) {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if page < 1 {
		page = 1
	}
	if pageSize > 100 {
		pageSize = 100
	}
	if pageSize < 10 {
		pageSize = 10
	}

	data, err := model.GameFullTextMeili(ty, page, pageSize, platformId, tagId, w)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

func (that *GameController) Rec(ctx *fasthttp.RequestCtx) {

	ty := ctx.QueryArgs().GetUintOrZero("ty")
	page := ctx.QueryArgs().GetUintOrZero("page")
	hot := ctx.QueryArgs().GetUintOrZero("hot")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	platformId := string(ctx.QueryArgs().Peek("platform_id"))
	gameName := string(ctx.QueryArgs().Peek("br_alias"))

	//if !helper.CtypeDigit(platformId) {
	//	helper.Print(ctx, false, helper.ParamErr)
	//	return
	//}

	if page < 1 {
		page = 1
	}

	if pageSize > 100 {
		pageSize = 100
	}

	var data model.GameData
	var err error

	if gameName != "" {
		data, err = model.GameListQuery(ctx, ty, hot, page, pageSize, platformId, gameName, "is_new")
	} else {
		data, err = model.GameListMeili(ctx, ty, hot, page, pageSize, platformId, gameName, "is_new")
	}
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

func (that *GameController) Hot(ctx *fasthttp.RequestCtx) {

	ty := ctx.QueryArgs().GetUintOrZero("ty")
	hot := ctx.QueryArgs().GetUintOrZero("hot")
	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	platformId := string(ctx.QueryArgs().Peek("platform_id"))
	gameName := string(ctx.QueryArgs().Peek("br_alias"))

	if !helper.CtypeDigit(platformId) {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if page < 1 {
		page = 1
	}

	if pageSize > 100 {
		pageSize = 100
	}

	var data model.GameData
	var err error
	hot = 1
	if gameName != "" {
		data, err = model.GameListQuery(ctx, ty, hot, page, pageSize, platformId, gameName, "is_hot")
	} else {
		data, err = model.GameListMeili(ctx, ty, hot, page, pageSize, platformId, "", "is_hot")
	}
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

func (that *GameController) Fav(ctx *fasthttp.RequestCtx) {

	ty := ctx.QueryArgs().GetUintOrZero("ty")
	hot := ctx.QueryArgs().GetUintOrZero("hot")
	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")

	platformId := string(ctx.QueryArgs().Peek("platform_id"))

	if !helper.CtypeDigit(platformId) {
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	if page < 1 {
		page = 1
	}

	if pageSize > 100 {
		pageSize = 100
	}

	data, err := model.GameListMeili(ctx, ty, hot, page, pageSize, platformId, "", "is_fav")
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)

}

// 游戏列表
func (that *GameController) List(ctx *fasthttp.RequestCtx) {
	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	gameType := ctx.QueryArgs().GetUintOrZero("game_type")
	isHot := ctx.QueryArgs().GetUintOrZero("is_hot")
	isNew := ctx.QueryArgs().GetUintOrZero("is_new")
	tagId := string(ctx.QueryArgs().Peek("tag_id"))

	platformId := string(ctx.QueryArgs().Peek("platform_id"))

	//if !helper.CtypeDigit(platformId) {
	//	helper.Print(ctx, false, helper.ParamErr)
	//	return
	//}

	if page < 1 {
		page = 1
	}

	if pageSize > 100 {
		pageSize = 100
	}

	filter := "online = 1"

	if isHot > 0 {
		filter = " AND is_hot = 1"
	}
	if isNew > 0 {
		filter += " AND is_new = 1"
	}
	if gameType != 0 {
		filter += fmt.Sprintf(" AND game_type = %d", gameType)
	}
	if platformId != "0" {
		// 如果 platformId 包含逗号，则进行多个平台ID的查询
		if strings.Contains(platformId, ",") {
			// 如果 platformId 包含逗号，则构建多个平台ID的过滤条件
			platformIds := strings.Split(platformId, ",")
			platformFilters := make([]string, len(platformIds))
			for i, id := range platformIds {
				platformFilters[i] = fmt.Sprintf("platform_id = %s", id)
			}
			filter += " AND (" + strings.Join(platformFilters, " OR ") + ")"
		} else {
			// 否则，构建单个平台ID的过滤条件
			filter += fmt.Sprintf(" AND platform_id = %s", platformId)
		}

		//filter += fmt.Sprintf(" AND platform_id = %s", platformId)
	}
	if tagId != "0" && tagId != "" {
		filter += fmt.Sprintf(" AND tag_ids = %s", tagId)
	}

	data, err := model.GameList(ctx, page, pageSize, filter)
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

// 启动游戏
func (that *GameController) Launch(ctx *fasthttp.RequestCtx) {
	param := map[string]string{}
	pid := string(ctx.QueryArgs().Peek("pid"))
	code := string(ctx.QueryArgs().Peek("code"))
	gtype := ctx.QueryArgs().GetUintOrZero("game_type")

	helper.InfoLog("pid:%s", pid)
	helper.InfoLog("code:%s", code)
	helper.InfoLog("gtype:%d", gtype)

	d := string(ctx.Request.Header.Peek("d"))

	i, err := strconv.Atoi(d)
	if err != nil {
		helper.Print(ctx, false, helper.DeviceTypeErr)
		return
	}

	if _, ok := model.Devices[i]; !ok {
		helper.Print(ctx, false, helper.DeviceTypeErr)
		return
	}

	uid := myUserHelp.GetUidFromToken(ctx)

	if uid == "" {
		helper.Print(ctx, false, helper.AccessTokenExpires)
		return
	}

	if myUserHelp.GetMemberTester(uid) == 0 {
		helper.Print(ctx, false, helper.UserNotExist)
		return
	}

	GameType, _ := strconv.Atoi(pid)
	GameType = GameType / 10 * 10
	GameTypeStr := strconv.Itoa(GameType)
	if myUserHelp.GetMemberTester(uid) == 2 &&
		(GameTypeStr != helper.PG) &&
		(GameTypeStr != helper.PP) &&
		(GameTypeStr != helper.JDB) &&
		(GameTypeStr != helper.PASPOUCASH) &&
		(GameTypeStr != helper.JILI) {
		helper.Print(ctx, false, helper.Blocked)
		return
	}

	if myUserHelp.GetMemberState(uid) == 2 {
		helper.Print(ctx, false, helper.Blocked)
		return
	}

	if myUserHelp.G_UserButton.GetGameButton(uid) == myUserHelp.ButtonClose {
		helper.Print(ctx, false, helper.CfgErrStartGame)
		return
	}

	online := myConfig.FindGameOnlineState(code)
	if online != 1 {
		helper.Print(ctx, false, helper.GameTypeErr)
		return
	}

	platF, err := model.PlatformSql(pid)
	if err != nil {
		helper.Print(ctx, false, helper.PlatIDErr)
		return
	}
	if platF.Maintained == 2 {
		helper.Print(ctx, false, helper.PlatformMaintain)
		return
	}

	maintained := myConfig.FindGameMaintainedState(code)
	if maintained == 2 {
		helper.Print(ctx, false, helper.PlatformMaintain)
		return
	}
	//场馆原始id
	platformId := pid //三方场馆的ID
	BiglatformIdInt, _ := strconv.Atoi(pid)
	BiglatformIdInt = BiglatformIdInt / 10 * 10
	BiglatformIdString := strconv.Itoa(BiglatformIdInt)
	param["uid"] = uid
	param["gtype"] = strconv.Itoa(gtype)
	param["gameid"] = code
	param["test"] = fmt.Sprintf("%d", myUserHelp.GetMemberTester(uid)) // 1 正式账号 2 模拟账号

	//查询假pg开关是否打开
	helper.InfoLog("BiglatformIdString:%s", BiglatformIdString)
	RtpControlWay := myUserHelp.G_UserButton.GetRtpControlWay(uid)
	RtpControlWay = RtpControlWay % 10

	if BiglatformIdString == helper.PASPOUCASH {
		RtpControlWay := myUserHelp.G_UserButton.GetRtpControlWay(uid)
		RtpControlWay = RtpControlWay % 10
		var fakepgRtp int = 0
		if RtpControlWay == 0 {
			sqlSelect := fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and operator_id=%s	and game='%s'"+
				"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(uid), myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
			err := model.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
			if err != nil {
				if err.Error() != "sql: no rows in result set" {
					helper.SqlSelectErrLog(sqlSelect)
				}

				fakepgRtp = myConfig.GetOperatorInitRtp(myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
				if fakepgRtp == 0 {
					sqlSelect = fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and operator_id=%s and game='%s'"+
						"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(uid), myConfig.Def_Channel, BiglatformIdString)
					err = model.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
					if err != nil {
						fakepgRtp = myConfig.GetOperatorInitRtp(myConfig.Def_Channel, BiglatformIdString)
					}
				}
			}
		} else if RtpControlWay == 2 {
			fakepgRtp = myUserHelp.G_UserButton.GetFakePGRtp(uid)
		}

		param["gtype"] = fmt.Sprintf("%d", fakepgRtp)
		AdjustRtp, AdjustMoneyMul := myConfig.GetOperatorAdjustInfo(myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
		param["FakePgRTPMulti"] = strconv.Itoa(AdjustRtp)
		param["FakePgRTPValue"] = strconv.Itoa(AdjustMoneyMul)
	} else {
		fakePlatformId, fakePgId, bGet := myConfig.GetFakeGamePlatformByPrior(BiglatformIdString, code, param["test"])
		//bCanEntry := myConfig.CanEntryFakceGameByChannelId(myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
		helper.InfoLog("PlatformByPrior:%s--%s--%v---%v", fakePlatformId, fakePgId, bGet)

		if bGet { //&& bCanEntry
			param["gameid"] = fakePgId
			platformId = fakePlatformId
			var fakepgRtp int = 0
			if RtpControlWay == 0 {
				sqlSelect := fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and operator_id=%s	and game='%s'"+
					"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(uid), myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
				err := model.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
				if err != nil {
					if err.Error() != "sql: no rows in result set" {
						helper.SqlSelectErrLog(sqlSelect)
					}

					fakepgRtp = myConfig.GetOperatorInitRtp(myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
					if fakepgRtp == 0 {
						sqlSelect = fmt.Sprintf("Select rtp FROM tbl_cfg_fake_rtp WHERE money<=%0.2f and operator_id=%s and game='%s'"+
							"order by money desc limit 1", myUserHelp.GetBalanceFloat64ByUid(uid), myConfig.Def_Channel, BiglatformIdString)
						err = model.GetMasterDBInstance().Get(&fakepgRtp, sqlSelect)
						if err != nil {
							fakepgRtp = myConfig.GetOperatorInitRtp(myConfig.Def_Channel, BiglatformIdString)
						}
					}
				}
			} else if RtpControlWay == 2 {
				/*
					if BiglatformIdString == helper.PG {
						fakepgRtp = myUserHelp.G_UserButton.GetFakePGRtp(uid)
					} else if BiglatformIdString == helper.PP {
						fakepgRtp = myUserHelp.G_UserButton.GetFakePPRtp(uid)
					} else if BiglatformIdString == helper.JILI {
						fakepgRtp = myUserHelp.G_UserButton.GetFakeJILIRtp(uid)
					} else if BiglatformIdString == helper.JDB {
						fakepgRtp = myUserHelp.G_UserButton.GetFakeJDBRtp(uid)
					} else {
						fakepgRtp = myUserHelp.G_UserButton.GetFakePGRtp(uid)
					}
				*/

				fakepgRtp = myUserHelp.G_UserButton.GetFakePGRtp(uid)
			}

			param["gtype"] = fmt.Sprintf("%d", fakepgRtp)
			AdjustRtp, AdjustMoneyMul := myConfig.GetOperatorAdjustInfo(myUserHelp.GetMemberOperatorId(uid), BiglatformIdString)
			param["FakePgRTPMulti"] = strconv.Itoa(AdjustRtp)
			param["FakePgRTPValue"] = strconv.Itoa(AdjustMoneyMul)
		} else {
			//目前没有真的游戏 如果没有找到对应的表就直接返回
			helper.Print(ctx, false, helper.PlatformMaintain)
			return
		}
	}

	//打印RTP
	helper.InfoLog("Rtp log:%s----%s", uid, param["gtype"])
	content, err := model.Launch(param, platformId)

	jsonContent, _ := helper.JsonMarshal(content)
	helper.InfoLog("content:%s", jsonContent)

	if err != nil {
		//登录失败
		helper.SqlSelectErrLog("QueryArgs:%s,", ctx.QueryArgs(), "content:", content)
		if content.Msg == helper.EvoEnterLimitErr {
			helper.Print(ctx, false, content)
		} else {
			helper.Print(ctx, false, err.Error())
		}

		return
	}

	helper.Print(ctx, true, content.Data)
}

// 游戏返回参数处理
func (that *GameController) GameTransaction(ctx *fasthttp.RequestCtx) {
	//{"cmd":1001,"sign":"0fcff9bcb5e508129492105437499a61","content":{"uid":"35"}}
	now := time.Now()
	param := model.GameParam{}
	data := ctx.PostBody()

	err := json.Unmarshal(data, &param)
	if err != nil {
		helper.GetloggerInstance().Warning(string(data))
		helper.Print(ctx, false, helper.ParamErr)
		return
	}

	jsonvalue, _ := json.Marshal(param.Content)
	content := string(jsonvalue)
	resp, status := model.Transaction(param, content)
	helper.Print(ctx, status, resp)
	now1 := time.Now()
	pastMilli := now1.UnixMilli() - now.UnixMilli()
	if pastMilli >= 150 {
		helper.InfoLog("over time:%d---%s", pastMilli, string(data))
	}
}

// 游戏数量
func (that *GameController) Number(ctx *fasthttp.RequestCtx) {

	data, err := model.GameNumber()
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}

// List 场馆列表
func (that *GameController) PlatformsList(ctx *fasthttp.RequestCtx) {

	data, err := model.PlatformList()
	if err != nil {
		helper.Print(ctx, false, err.Error())
		return
	}

	helper.Print(ctx, true, data)
}
